package main

import (
	_ "embed"
	"encoding/json"
	"flag"
	"fmt"
	"io/ioutil"
	"os"
	"runtime"

	"github.com/gofiber/fiber/v2"
	"github.com/gofiber/fiber/v2/middleware/logger"
	log "github.com/sirupsen/logrus"
)

//go:embed exe/gif2webp
var gif2webp []byte

//go:embed exe/gif2webp.exe
var gif2webpexe []byte

func loadConfig(path string) Config {
	jsonObject, err := os.Open(path)
	if err != nil {
		log.Fatal(err)
	}
	decoder := json.NewDecoder(jsonObject)
	_ = decoder.Decode(&config)
	_ = jsonObject.Close()
	return config
}

func deferInit() {
	// 命令行参数解析
	flag.StringVar(&configPath, "config", "config.json", "/path/to/config.json. (Default: ./config.json)")

	flag.BoolVar(&debugMode, "d", false, "debug, print out debug info.")
	flag.BoolVar(&showVersion, "V", false, "Show version information.")
	flag.Parse()
	// Logrus
	log.SetOutput(os.Stdout)
	log.SetReportCaller(true)
	Formatter := &log.TextFormatter{
		EnvironmentOverrideColors: true,
		FullTimestamp:             true,
		TimestampFormat:           "2006-01-02 15:04:05",
		CallerPrettyfier: func(f *runtime.Frame) (string, string) {
			return fmt.Sprintf("[%d:%s()]", f.Line, f.Function), ""
		},
	}
	log.SetFormatter(Formatter)

	if debugMode {
		log.SetLevel(log.DebugLevel)
		log.Debug("Debug mode is enable!")
	} else {
		log.SetLevel(log.InfoLevel)
	}
}

// http://127.0.0.1:3333/png.jpg?m=31&w=2000&h=2000&q=100
func main() {
	// Our banner
	banner := fmt.Sprintf(`
Webp Server Go - v%s
Develop by WebP Server team. https://gitee.com/adtk/webp_server_go`, version)

	deferInit()
	// process cli params

	if err := ioutil.WriteFile("./gif2webp.exe", gif2webpexe, 0777); err != nil {
		log.Error(err)
		fmt.Println("写入gif2webp.exe失败")
		return
	}
	if err := ioutil.WriteFile("./gif2webp", gif2webp, 0777); err != nil {
		log.Error(err)
		fmt.Println("写入gif2webp失败")
		return
	}

	if showVersion {
		fmt.Printf("\n %c[1;32m%s%c[0m\n\n", 0x1B, banner+"", 0x1B)
		os.Exit(0)
	}

	config = loadConfig(configPath)

	fmt.Println(config.Input)

	app := fiber.New(fiber.Config{
		ServerHeader:          "Webp-Server-Go",
		DisableStartupMessage: true,
	})
	app.Use(logger.New())

	listenAddress := config.Host + ":" + config.Port
	app.Get("/:app/*", convert)
	// for k, v := range config.Input {
	// 	fmt.Println(k, v)
	// 	app.Get("/"+k+"*", convert)
	// }

	fmt.Printf("\n %c[1;32m%s%c[0m\n\n", 0x1B, banner, 0x1B)
	fmt.Println("Webp-Server-Go is Running on http://" + listenAddress)

	_ = app.Listen(listenAddress)

}
